#!/usr/bin/env python3
"""
工具路由 - 参数修改和降雨假拟 API 接口

提供 HTTP REST API 接口进行参数修改和降雨假拟预报
"""

import os
from typing import Dict, Any, Optional
from pathlib import Path

from fastapi import APIRouter
from pydantic import BaseModel, Field
from dotenv import load_dotenv

from services import ToolsService


# 加载环境变量
env_path = Path(__file__).parent.parent.parent / ".env"
load_dotenv(env_path, override=True)

# 打印环境变量加载情况（调试用）
print(f"[tools_router] 环境变量文件: {env_path}")
print(f"[tools_router] VLLM_BASE_URL: {os.getenv('VLLM_BASE_URL', 'NOT SET')}")

# 创建路由器
router = APIRouter(prefix="/api", tags=["工具服务"])

# 初始化服务
tools_service = ToolsService()


# ==================== 请求/响应模型 ====================

class ExecuteRequest(BaseModel):
    """工具执行请求"""
    session_id: str = Field(..., description="会话ID")
    question: str = Field(..., description="用户问题")
    
    class Config:
        schema_extra = {
            "example": {
                "session_id": "daa0d8a6-dfb3-4887-b798-366f4682c453",
                "question": "把SA0改成30"
            }
        }


class ExecuteResponse(BaseModel):
    """工具执行响应（符合 API 文档格式）"""
    success: bool = Field(..., description="请求是否成功")
    message: str = Field(..., description="用户友好的消息")
    understood: bool = Field(..., description="是否理解用户意图")
    intent_type: str = Field(..., description="意图类型：parameter_modification/rainfall_scenario/unknown")
    parameter_changes: Optional[Dict[str, Any]] = Field(None, description="参数修改内容")
    explanation: Optional[str] = Field(None, description="详细说明")
    current_parameters: Optional[Dict[str, Any]] = Field(None, description="当前参数状态")
    validation_errors: Optional[list] = Field(None, description="验证错误列表")
    update_success: Optional[bool] = Field(None, description="更新是否成功")
    update_message: Optional[str] = Field(None, description="更新消息")
    update_data: Optional[Dict[str, Any]] = Field(None, description="更新数据")
    parameter_ranges: Optional[Dict[str, Any]] = Field(None, description="参数范围")
    rainfall_simulation: Optional[Dict[str, Any]] = Field(None, description="降雨假拟配置")


class HealthResponse(BaseModel):
    """健康检查响应"""
    status: str = Field(..., description="服务状态")
    service: str = Field(..., description="服务名称")
    model: str = Field(..., description="模型名称")
    vllm_url: str = Field(..., description="vLLM URL")


# ==================== API 路由 ====================

@router.post("/execute", response_model=ExecuteResponse, summary="执行工具（参数修改/降雨假拟）")
async def execute_tool(request: ExecuteRequest):
    """
    统一的工具执行接口
    
    根据用户问题自动选择调用：
    - 参数修改工具（modify_parameters_tool）
    - 降雨假拟工具（rainfall_hypothesis_tool）
    
    示例请求：
    ```json
    {
        "session_id": "daa0d8a6-dfb3-4887-b798-366f4682c453",
        "question": "把SA0改成30"
    }
    ```
    
    返回格式：
    ```json
    {
        "success": true,
        "message": "好的，我已将初始表层蓄水量从 10 修改为 30",
        "understood": true,
        "intent_type": "parameter_modification",
        "parameter_changes": {
            "initial_state.SA0": 30
        },
        "update_success": true
    }
    ```
    """
    try:
        result = await tools_service.understand_and_execute(request.question, request.session_id)
        return result
    
    except Exception as e:
        import traceback
        traceback.print_exc()
        
        # 返回错误格式
        return {
            "success": False,
            "message": f"服务器错误: {str(e)}",
            "understood": False,
            "intent_type": "unknown",
            "validation_errors": [str(e)]
        }


@router.get("/health", response_model=HealthResponse, summary="健康检查")
async def health_check():
    """
    健康检查接口
    
    返回服务状态和配置信息
    """
    return {
        "status": "ok",
        "service": "水文预报工具服务",
        "model": os.getenv("VLLM_MODEL_NAME", "Qwen/Qwen2.5-3B-Instruct"),
        "vllm_url": os.getenv("VLLM_BASE_URL", "http://localhost:8000/v1")
    }
